﻿
Ext.namespace('Yaxunsoft', 'Yaxunsoft.Common');
Yaxunsoft.Common.DateField = function(config) {
    this.plugins = [new Ext.ux.InputTextMask('9999-99-99', true)];
    Yaxunsoft.Common.DateField.superclass.constructor.call(this, config);
};
Ext.extend(Yaxunsoft.Common.DateField, Ext.form.DateField, {
    onRender: function(ct, position) {
        Yaxunsoft.Common.DateField.superclass.onRender.call(this, ct, position);
        if (this.name) {
            this.hiddenField = this.el.insertSibling({ tag: 'input', type: 'hidden', name: this.name, id: (this.hiddenId || this.name) },
                    'before', true);
            this.hiddenField.value =
                this.hiddenValue !== undefined ? this.hiddenValue :
                this.value !== undefined ? this.value : '';
            this.id = this.name;
            this.el.dom.removeAttribute('name');
        }
    },
    setValue: function(date) {
        Yaxunsoft.Common.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
        if (date) {
            var d = new Date(Date.parse(date));
            var value = "\/Date(" + d.getTime() + "+0800)\/";
            this.hiddenField.value = value;
        } else {
            this.hiddenField.value = '';
        }
    }
});
////
//选择日期和时间
////
Yaxunsoft.Common.TimeField = function(config) {
    this.dateTime = config.dateTime;
    this.plugins = [new Ext.ux.InputTextMask('99:99:99', true)];
    Yaxunsoft.Common.TimeField.superclass.constructor.call(this, config);
};

Ext.extend(Yaxunsoft.Common.TimeField, Ext.form.TimeField, {
    hideTrigger: true,
    minValue: '00:00:01',
    maxValue: '23:59:59',
    onRender: function(ct, position) {
        Yaxunsoft.Common.TimeField.superclass.onRender.call(this, ct, position);
        this.el.dom.removeAttribute('name');
//        var toolTip = this.toolTip;
//        Ext.QuickTips.register({ target: this, text: toolTip })
    },
    clearInvalid: function() {
        if (!this.rendered || this.preventMark) {
            return;
        }
        this.el.removeClass(this.invalidClass);
        this.dateTime.clearInvalid();
    },
    markInvalid: function(msg) {
        if (!this.rendered || this.preventMark) {
            return;
        }
        this.el.addClass(this.invalidClass);
        msg = msg || this.invalidText;
        this.dateTime.markInvalid(msg);
    }

});
Yaxunsoft.Common.DateField1 = function(config) {
    this.isReset = false;
    this.dateTime = config.dateTime;
    this.plugins = [new Ext.ux.InputTextMask('9999-99-99', true)];
    Yaxunsoft.Common.DateField1.superclass.constructor.call(this, config);
};
Ext.extend(Yaxunsoft.Common.DateField1, Ext.form.DateField, {
    onRender: function(ct, position) {
    Yaxunsoft.Common.DateField1.superclass.onRender.call(this, ct, position);
    this.el.dom.removeAttribute('name');
    },

    clearInvalid: function() {
        if (!this.rendered || this.preventMark) {
            return;
        }
        this.el.removeClass(this.invalidClass);
        this.dateTime.clearInvalid();
    },
    markInvalid: function(msg) {
        if (!this.rendered || this.preventMark) {
            return;
        }
        this.el.addClass(this.invalidClass);
        msg = msg || this.invalidText;
        this.dateTime.markInvalid(msg);
    }

});
Yaxunsoft.Common.DateTimeField = function(config) {

    this.messages = new Array();
    var dateTime = this;
    var dateConfig = Ext.apply({}, {
        // name: config.name + '-date', 
        format: config.dateFormat || Ext.form.DateField.prototype.format
            , width: config.dateWidth
            , selectOnFocus: config.selectOnFocus
            , dateTime: dateTime
            , listeners: {
                blur: { scope: this, fn: this.onBlur }
                 , focus: { scope: this, fn: this.onFocus }
            }
    }, config.dateConfig);
    this.df = new Yaxunsoft.Common.DateField1(dateConfig);
    var timeConfig = Ext.apply({}, {
        // name: config.name + '-time', 
        format: config.timeFormat || Ext.form.TimeField.prototype.format
            , width: config.timeWidth
            , selectOnFocus: config.selectOnFocus
            , dateTime: dateTime
            , listeners: {
                blur: { scope: this, fn: this.onBlur }
                 , focus: { scope: this, fn: this.onFocus }
            }
    }, config.timeConfig);
    this.tf = new Yaxunsoft.Common.TimeField(timeConfig);
    Yaxunsoft.Common.DateTimeField.superclass.constructor.call(this, config);
};
Ext.extend(Yaxunsoft.Common.DateTimeField, Ext.form.Field, {
    defaultAutoCreate: { tag: 'input', type: 'hidden' }
    , timeWidth: 80
    , dtSeparator: ' '
    , hiddenFormat: 'Y-m-d H:i:s'
    , otherToNow: true
    , timePosition: 'right' // valid values:'bellow', 'right'
    , dateFormat: 'm/d/y'
    , timeFormat: 'g:i A'
    , initComponent: function() {
        Yaxunsoft.Common.DateTimeField.superclass.initComponent.call(this);
        this.relayEvents(this.df, ['focus', 'specialkey', 'invalid', 'valid']);
        this.relayEvents(this.tf, ['focus', 'specialkey', 'invalid', 'valid']);


    }
    , onRender: function(ct, position) {
        if (this.isRendered) {
            return;
        }
        Yaxunsoft.Common.DateTimeField.superclass.onRender.call(this, ct, position);
        var t;
        if ('bellow' === this.timePosition) {
            t = Ext.DomHelper.append(ct, { tag: 'table', style: 'border-collapse:collapse', children: [
                 { tag: 'tr', children: [{ tag: 'td', style: 'padding-bottom:1px', cls: 'ux-datetime-date'}] }
                , { tag: 'tr', children: [{ tag: 'td', cls: 'ux-datetime-time'}] }
            ]
            }, true);
        }
        else {
            t = Ext.DomHelper.append(ct, { tag: 'table', style: 'border-collapse:collapse', children: [
                { tag: 'tr', children: [
                    { tag: 'td', style: 'padding-right:4px', cls: 'ux-datetime-date' }, { tag: 'td', cls: 'ux-datetime-time' }
                ]
                }
            ]
            }, true);
        }

        this.tableEl = t;
        this.wrap = t.wrap({ cls: 'x-form-field-wrap' });
        this.wrap.on("mousedown", this.onMouseDown, this, { delay: 10 });
        this.df.render(t.child('td.ux-datetime-date'));
        this.tf.render(t.child('td.ux-datetime-time'));
        if (Ext.isIE && Ext.isStrict) {
            t.select('input').applyStyles({ top: 0 });
        }

        this.on('specialkey', this.onSpecialKey, this);
        this.df.el.swallowEvent(['keydown', 'keypress']);
        this.tf.el.swallowEvent(['keydown', 'keypress']);
        if ('side' === this.msgTarget) {
            var elp = this.el.findParent('.x-form-element', 10, true);
            this.errorIcon = elp.createChild({ cls: 'x-form-invalid-icon' });

            this.df.errorIcon = this.errorIcon;
            this.tf.errorIcon = this.errorIcon;
        }
        this.isRendered = true;

    }
    , adjustSize: Ext.BoxComponent.prototype.adjustSize
    , alignErrorIcon: function() {
        this.errorIcon.alignTo(this.tableEl, 'tl-tr', [2, 0]);
    }
    , initDateValue: function() {
        this.dateValue = this.otherToNow ? new Date() : new Date(1970, 0, 1, 0, 0, 0);
    }
    , disable: function() {
        if (this.isRendered) {
            this.df.disabled = this.disabled;
            this.df.onDisable();
            this.tf.onDisable();
        }
        this.disabled = true;
        this.df.disabled = true;
        this.tf.disabled = true;
        this.fireEvent("disable", this);
        return this;
    }
    , enable: function() {
        if (this.rendered) {
            this.df.onEnable();
            this.tf.onEnable();
        }
        this.disabled = false;
        this.df.disabled = false;
        this.tf.disabled = false;
        this.fireEvent("enable", this);
        return this;
    }
    , focus: function() {
        this.df.focus();
    }
    , getPositionEl: function() {
        return this.wrap;
    }
    , getResizeEl: function() {
        return this.wrap;
    }
    , getValue: function() {
        return this.dateValue ? new Date(this.dateValue) : '';
    }
    , isValid: function() {
        return this.df.isValid() && this.tf.isValid();
    }
    , isVisible: function() {
        return this.df.rendered && this.df.getActionEl().isVisible();
    }
    , onBlur: function(f) {
        if (this.wrapClick) {
            f.focus();
            this.wrapClick = false;
        }

        if (f === this.df) {
            this.updateDate();
        }
        else {
            this.updateTime();
        }
        this.updateHidden();
        (function() {
            if (!this.df.hasFocus && !this.tf.hasFocus) {
                var v = this.getValue();
                if (String(v) !== String(this.startValue)) {
                    this.fireEvent("change", this, v, this.startValue);
                }
                this.hasFocus = false;
                this.fireEvent('blur', this);
            }
        }).defer(100, this);

    }
    , onFocus: function() {
        if (!this.hasFocus) {
            this.hasFocus = true;
            this.startValue = this.getValue();
            this.fireEvent("focus", this);
        }
    }
    , onMouseDown: function(e) {
        this.wrapClick = 'td' === e.target.nodeName.toLowerCase();
    }
    , onSpecialKey: function(t, e) {
        var key = e.getKey();
        if (key == e.TAB) {
            if (t === this.df && !e.shiftKey) {
                e.stopEvent();
                this.tf.focus();
            }
            if (t === this.tf && e.shiftKey) {
                e.stopEvent();
                this.df.focus();
            }
        } if (key == e.ENTER) {
            this.updateValue();
        }

    }
    , setDate: function(date) {
        this.df.setValue(date);
    }
    , setTime: function(date) {
        this.tf.setValue(date);
    }
    , setSize: function(w, h) {
        if (!w) {
            return;
        }
        if ('bellow' == this.timePosition) {
            this.df.setSize(w, h);
            this.tf.setSize(w, h);
            if (Ext.isIE) {
                this.df.el.up('td').setWidth(w);
                this.tf.el.up('td').setWidth(w);
            }
        }
        else {
            this.df.setSize(w - this.timeWidth - 4, h);
            this.tf.setSize(this.timeWidth, h);

            if (Ext.isIE) {
                this.df.el.up('td').setWidth(w - this.timeWidth - 4);
                this.tf.el.up('td').setWidth(this.timeWidth);
            }
        }
    }
    , setValue: function(val) {
        if (val) {
            val = new Date(val.getTime() - 8 * 60 * 60000);
        }
        //       alert(val.toLocaleString());
        if (!val && true === this.emptyToNow) {
            this.setValue(new Date());
            return;
        }
        else if (!val) {
            this.setDate('');
            this.setTime('');
            this.updateValue();
            return;
        }
        val = val ? val : new Date(1970, 0, 1, 0, 0, 0);
        var da, time;
        if (val instanceof Date) {
            this.setDate(val);
            this.setTime(val);
            this.dateValue = new Date(val);
        } else if (val instanceof Object && val.time) {
            var dtDate = new Date(parseInt(val.time));
            this.setDate(dtDate);
            this.setTime(dtDate);
            this.dateValue = new Date(dtDate);
        }
        else {
            da = val.split(this.dtSeparator);
            this.setDate(da[0]);
            if (da[1]) {
                this.setTime(da[1]);
            }
        }
        this.updateValue();
    }
    , setVisible: function(visible) {
        if (visible) {

            this.df.show();
            this.tf.show();


        } else {
            this.df.hide();
            this.tf.hide();
        }
        return this;
    }
    ,
    reset: function() {
        this.df.reset();
        this.tf.reset();
        this.clearInvalid();
    },
    show: function() {

        return this.setVisible(true);
    }
    , hide: function() {

        return this.setVisible(false);
    }
    , updateDate: function() {

        var d = this.df.getValue();
        if (d) {
            if (!(this.dateValue instanceof Date)) {
                this.initDateValue();
                if (!this.tf.getValue()) {
                    this.setTime(this.dateValue);
                }
            }
            this.dateValue.setMonth(0);
            this.dateValue.setFullYear(d.getFullYear());
            this.dateValue.setMonth(d.getMonth());
            this.dateValue.setDate(d.getDate());
        }
        else {
            this.dateValue = '';
            this.setTime('');
        }
    }
    , updateTime: function() {
        var t = this.tf.getValue();
        if (t && !(t instanceof Date)) {
            t = Date.parseDate(t, this.tf.format);
        }
        if (t && !this.df.getValue()) {
            this.initDateValue();
            this.setDate(this.dateValue);
        }
        if (this.dateValue instanceof Date) {
            if (t) {
                this.dateValue.setHours(t.getHours());
                this.dateValue.setMinutes(t.getMinutes());
                this.dateValue.setSeconds(t.getSeconds());
            }
            else {
                this.dateValue.setHours(0);
                this.dateValue.setMinutes(0);
                this.dateValue.setSeconds(0);
            }
        }
    }
    , updateHidden: function() {
        if (this.isRendered) {
            var value = this.dateValue instanceof Date ? this.dateValue.format(this.hiddenFormat) : '';
            // alert(value);
            if (value) {
                var d = new Date(Date.parse(value.replace(/-/g, "/")));
                //  alert();
                this.el.dom.value = "\/Date(" + d.getTime() + "+0800)\/";
            } else {
                this.el.dom.value = "";
            }
        }
    }
    , updateValue: function() {

        this.updateDate();
        this.updateTime();
        this.updateHidden();

        return;
    }
    , validate: function() {
        return this.df.validate() && this.tf.validate();
    }
    , renderer: function(field) {

        var format = field.editor.dateFormat || Yaxunsoft.Common.DateTimeField.prototype.dateFormat;
        format += ' ' + (field.editor.timeFormat || Yaxunsoft.Common.DateTimeField.prototype.timeFormat);
        var renderer = function(val) {
            var retval = Ext.util.Format.date(val, format);
            return retval;
        };
        return renderer;
    },
    markInvalid: function(msg) {
        this.messages.push(msg);
        Yaxunsoft.Common.DateTimeField.superclass.markInvalid.call(this, msg);
    },
    clearInvalid: function() {
        this.messages.pop();
        if (this.messages.length == 0) {
            Yaxunsoft.Common.DateTimeField.superclass.clearInvalid.call(this);
        }
        else {
            var msg = this.messages.pop();
            this.markInvalid(msg);
        }
    }
});
Ext.reg('xdatetime', Yaxunsoft.Common.DateTimeField);

